import os
from collections import OrderedDict

from django.conf import settings
from django.template import loader

from advertising.models import ContentCategory
from celery_tasks.main import app
from goods.models import SKU
from goods.utils import get_categories


# 生成商品列表页的异步任务
@app.task(name='generate_static_list_html')
def generate_static_list_html():
    categories = get_categories()
    # print(categories)

    # 渲染模板
    context = {
        'categories': categories,
    }
    template = loader.get_template('list.html')
    # 保存页面内容到index前端页面中
    html_text = template.render(context)
    file_path = os.path.join(settings.GENERATED_STATIC_HTML_FILES_DIR, 'list.html')
    with open(file_path, 'w', encoding='utf-8') as f:
        f.write(html_text)


# 定义生成商品详情页的异步任务
@app.task(name='generate_static_datail_html')
def generate_static_detail_html(sku_id):
    # 获取商品的分类信息
    categories = get_categories()
    # 根据请求的商品id找到商品的详细信息,并通过商品找到其对应的图片信息
    sku = SKU.objects.get(id=sku_id)
    sku.image = sku.skuimage_set.all()
    # 获取商品的频道信息
    goods = sku.goods
    goods.channel = goods.category1.goodschannel_set.all()[0]
    # 获取当前商品的详细规格
    sku_spes = sku.skuspecification_set.order_by('spec_id')
    # 定义一个空列表用来储存商品规格信息
    sku_key = []
    # 遍历所有的商品的规格数,将其存入列表中
    for spes in sku_spes:
        sku_key.append(spes.option.id)
    # 获取当前频道的所有商品
    skus = goods.sku_set.all()
    # 定义一个字典用来储存商品的详细的规格参数
    spec_sku_map = {}
    # 遍历每一个商品,按照规格排序
    for s in skus:
        # 获取sku的规格参数
        s_specs = s.skuspecification_set.order_by('spec_id')
        # 用于形成规格参数-sku字典的键
        key = []
        for spec in s_specs:
            key.append(spec.option.id)
        # 向规格参数-sku字典添加记录
        spec_sku_map[tuple(key)] = s.id

    # 获取当前商品的规格信息
    specs = goods.goodsspecification_set.order_by('id')
    # 若当前sku的规格信息不完整，则不再继续
    if len(sku_key) < len(specs):
        return
    for index, spec in enumerate(specs):
        # 复制当前sku的规格键
        key = sku_key[:]
        # 该规格的选项
        options = spec.specificationoption_set.all()
        for option in options:
            # 在规格参数sku字典中查找符合当前规格的sku
            key[index] = option.id
            option.sku_id = spec_sku_map.get(tuple(key))

        spec.options = options
        # 渲染模板，生成静态html文件
    context = {
            'categories': categories,
            'goods': goods,
            'specs': specs,
            'sku': sku
        }

    template = loader.get_template('detail.html')
    html_text = template.render(context)
    file_path = os.path.join(settings.GENERATED_STATIC_HTML_FILES_DIR, 'goods/' + str(sku_id) + '.html')
    with open(file_path, 'w') as f:
        f.write(html_text)